namespace SimpleWebServices.Web.UI.Html.Elements
{
    using System;
    using System.Xml.Serialization;
    using SimpleWebServices.Web.UI.Html.Validation;

    [XmlRoot("fieldset")]
    public class Fieldset : InnerElements, IValidation, IXmlSerializable
    {
        public Fieldset()
        {
        }

        public Fieldset(Name id)
            : this(id, null as string)
        {
            this.Id = id;
        }

        public Fieldset(Name id, string legend)
        {
            this.Id = id;
            if (null != legend)
            {
                this.Elements.Add(new Legend
                {
                    Id = "legend-" + id,
                    Elements =
                    {
                        new TextString(legend)
                    }
                });
            }
        }

        public Fieldset(Name id, Legend legend)
        {
            this.Id = id;
            this.Elements.Add(legend);
        }

        public bool IsValid
        {
            get
            {
                bool value = true;

                if (null != this.Validator)
                {
                    value = this.Validator.Validate(this);
                }

                return value;
            }
        }

        public IValidate Validator
        {
            get;
            set;
        }

        public override IElement Deserialize(string name, string type, string xml)
        {
            IElement result = null;

            if (null == type && "fieldset".Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                result = xml.Deserialize<Fieldset>();
            }

            return result;
        }
    }
}